<template>
    <div>
      <!-- 搜索输入框 -->
        <form action="/">
          <van-search
            clearable
            :autofocus="true"
            v-model="value"
            show-action
            placeholder="请输入搜索关键词"
            @search="onSearch"
            @cancel="onCancel"
          />
        </form>
        <!-- 历史记录 -->
          <van-cell-group v-if="flag">
            <van-cell  :title="item.name" :value="item.ctime.split('T')[0]" v-for="item in hislist" :key="item.id" />
            <!-- <van-cell title="单元格" value="内容" label="描述信息" /> -->
          </van-cell-group>
          <!-- 搜索历史 -->
        <div v-else class="top" >
          <p>搜索历史<i @click="remove" class="iconfont icon-shanchu"></i></p>
          <van-tag v-for="(item,i) in val" :key="i">{{item}}</van-tag>
          <van-divider :style="{ padding: '0 50px' }" :hairline="false">暂无搜索历史</van-divider>
        </div>
        </div>
</template>
<script>
export default {
  data () {
    return {
      // 输入框的值
      value: '',
      // 将输入框的值保存在val数组中
      val: [],
      // 历史列表
      hislist: [],
      // 判断是否显示搜索历史
      flag: false
    }
  },
  mounted () {

  },
  methods: {
    // 点击回车触发
    async onSearch () {
      const { data: res } = await this.$http.get('/api/getprodlist')
      // console.log(res)
      if (res.status !== 0) return false
      this.hislist = res.message
      // 判断输入框的值是否跟val数组中存储的历史重复
      if (this.val.findIndex(item => item === this.value) === -1) {
        this.val.push(this.value)
        this.value = ''
        this.flag = true
      } else {
        this.value = ''
        this.flag = true
      }
    },
    // 点击取消按钮触发
    onCancel () {
      this.hislist = []
      this.flag = false
    },
    // 点击删除历史记录
    remove () {
      this.val = []
    }
  }
}
</script>
<style scoped lang="less">
.top p {
  margin: 0 10px
}
.icon-shanchu {
    float: right
  }
.van-tag {
  margin: 4px
}
</style>
